

const socketIO = require('socket.io')
let list = []
let cursorList = []
module.exports = function (server) {
    const io = socketIO(server, {
        cors: {
            origin: '*'
        }
    })

    io.on('connection', socket => {
        cursorList.push(socket.id)
        // io.sockets.emit('init', cursorList)
        /* 首次登陆发送聊天记录 */
        io.sockets.emit('join', cursorList)
        socket.emit(socket.id, {
            history: list
        })
        socket.on("mousemove", (data) => {
            io.sockets.emit('mouse-move', {
                left: data.left,
                top: data.top,
                id: socket.id,
                cursorList
            })
        })
        socket.on("clear", () => {
            socket.emit('reload', list)
        })
        socket.on('message', (data) => {
            let msg = {
                msg: JSON.parse(data),
                time: new Date().toLocaleString(),
            }
            /* 最多容纳一百条消息 */
            if (list.length > 500) {
                  list.shift()
            }
            list.push(msg)
            io.sockets.emit('broadcast_msg', msg)
        })

        socket.on('disconnect', () => {
            cursorList = cursorList.filter(id => {
                return id !== socket.id
            })
            io.sockets.emit('on-disconnect', socket.id)
        });
    });
}